package com.zz.hhbl.ui.podcast

import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.SeekBar
import androidx.activity.viewModels
import androidx.constraintlayout.motion.widget.MotionLayout
import androidx.constraintlayout.motion.widget.MotionLayout.TransitionListener
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.model.LatLng
import com.chad.library.adapter4.QuickAdapterHelper
import com.zz.framework.core.adapter.KotlinAdapter
import com.zz.framework.core.base.BaseActivity
import com.zz.framework.core.entity.PausePodcastEvent
import com.zz.framework.core.event.ShowLockSceenEvent
import com.zz.framework.core.ext.addHorizontalDividerItemDecoration
import com.zz.framework.core.ext.dp
import com.zz.framework.core.ext.fromJson
import com.zz.framework.core.ext.getFloat
import com.zz.framework.core.ext.gone
import com.zz.framework.core.ext.loadUrl
import com.zz.framework.core.ext.onClick
import com.zz.framework.core.ext.postDelayed
import com.zz.framework.core.ext.scrollToPositionWithOffset
import com.zz.framework.core.ext.toLanguage
import com.zz.framework.core.ext.viewBinding
import com.zz.framework.core.ext.visibility
import com.zz.framework.core.ext.visible
import com.zz.framework.core.utils.IntentBuilder
import com.zz.framework.core.utils.MediaPlayerUtils
import com.zz.framework.core.utils.language.LanguageManager
import com.zz.framework.core.utils.language.Strings
import com.zz.framework.core.xdialog.XDialog
import com.zz.framework.core.xdialog.listener.OnBindViewListener
import com.zz.framework.widget.musicplayer.MusicPlayerView
import com.zz.hhbl.R
import com.zz.hhbl.adapter.PlaceHolderAdapter
import com.zz.hhbl.config.GlobalCache
import com.zz.hhbl.databinding.ActivityMainBinding
import com.zz.hhbl.databinding.FragmentPodcastDetailBinding
import com.zz.hhbl.databinding.ItemPodcastBinding
import com.zz.hhbl.databinding.ItemPodcastTextDescriptionBinding
import com.zz.hhbl.databinding.ViewAudioPalyerBinding
import com.zz.hhbl.entity.LectureContentEntity
import com.zz.hhbl.entity.SpotInfoEntity
import com.zz.hhbl.entity.TourGuideCommentaryEntity
import com.zz.hhbl.event.OnLanguageSwitchEvent
import com.zz.hhbl.event.ScanResultEvent
import com.zz.hhbl.event.SearchResultEvent
import com.zz.hhbl.ui.CommonViewModel
import com.zz.hhbl.ui.SearchFragment
import com.zz.hhbl.ui.ai.AiActivity
import com.zz.hhbl.ui.qrcodescan.ScanActivity
import com.zz.hhbl.ui.setting.SettingFragment
import com.zz.hhbl.ui.translate.TranslateActivity
import com.zz.hhbl.utils.LocalUrlUtils
import com.zz.hhbl.utils.location.LocationResult
import com.zz.hhbl.utils.location.LocationViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/2/21 12:58.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
@AndroidEntryPoint
class MainActivity : BaseActivity() {
    private val viewModel: CommonViewModel by viewModels()
    private val binding: ActivityMainBinding by viewBinding()
    private val locationViewModel: LocationViewModel by viewModels()
    var speed = 1f
    var isSeekBarChanging = false
    var totalDuration = 1
    var currentDuration = 0
    var currentPosition = 0
    var currentSelectTextPosition = 0
    var isPlay = true
    private var mAdapter: KotlinAdapter<TourGuideCommentaryEntity, ItemPodcastBinding>? = null
    var mDetailAdapter: KotlinAdapter<LectureContentEntity, *>? = null
    var playBinding: ViewAudioPalyerBinding? = null
    var mPodcastDetailBinding: FragmentPodcastDetailBinding? = null
    var mTourGuideCommentaryList: List<TourGuideCommentaryEntity> = GlobalCache.getTourGuideCommentary()

    override fun initObserver() {
        viewModel.getChatTokenConfigLiveData.observe(this) {
            pausePlayMusic()
            dismissProgress()
            if (LanguageManager.currentLangCode == "en") {
                IntentBuilder.Builder().setClass(this, TranslateActivity::class.java).startActivity()
            } else {
                IntentBuilder.Builder().setClass(this, AiActivity::class.java).startActivity()
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        binding.apply {
            mainBottomBar.btnSetting.setText(Strings.更多.toLanguage())
            mainBottomBar.btnScan.setText(Strings.景点扫码.toLanguage())
            mainBottomBar.btnAi.setText(if (LanguageManager.currentLangCode == "en") Strings.AI翻译.toLanguage() else Strings.AI对话.toLanguage())
            mainBottomBar.ivLhh.setImageResource(R.mipmap.lhh)
            val mSpotInfo: SpotInfoEntity? = GlobalCache.getSpotInfo()
            mSpotInfo?.welcomeData?.firstOrNull()?.let {
                ivBackground.loadUrl(it.url.orEmpty())
            }
            recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    if (dy > 0) {
                        // 上滑
                        if (binding.topLayout.currentState != R.id.end) {
                            binding.topLayout.transitionToState(R.id.end)
                        }
                    }
//                    else if (dy < 0) {
//                        // 下滑
//                        val layoutManager = recyclerView.layoutManager as LinearLayoutManager
//                        if (layoutManager.findFirstCompletelyVisibleItemPosition() == 0 && binding.topLayout.currentState != R.id.start) {
//                            binding.topLayout.transitionToState(R.id.start)
//                        }
//                    }
                }
            })
            binding.mainBottomBar.motionLayout.setTransitionListener(object : TransitionListener {
                override fun onTransitionStarted(motionLayout: MotionLayout?, startId: Int, endId: Int) {
                }

                override fun onTransitionChange(motionLayout: MotionLayout?, startId: Int, endId: Int, progress: Float) {
                }

                override fun onTransitionCompleted(motionLayout: MotionLayout?, currentId: Int) {
                    if (currentId == R.id.expand) {
                        binding.mainBottomBar.ivArrow.setImageResource(R.drawable.vector_collapse)
                        binding.mainBottomBar.bottomBar.setBackgroundResource(R.drawable.shape_top_corner_9_white_bg)
                        mainBottomBar.ivLhh.setImageResource(if (LanguageManager.currentLangCode == "en") R.drawable.vector_main_translate else R.mipmap.lhh)
                    } else if (currentId == R.id.collapse) {
                        binding.mainBottomBar.ivArrow.setImageResource(R.drawable.vector_expand)
                        binding.mainBottomBar.bottomBar.setBackgroundResource(R.drawable.shape_top_right_corner_9_white_bg)
                        mainBottomBar.ivLhh.setImageResource(R.mipmap.lhh)
                    }
                }

                override fun onTransitionTrigger(motionLayout: MotionLayout?, triggerId: Int, positive: Boolean, progress: Float) {
                }
            })
            binding.mainBottomBar.btnScan.onClick {
                pausePlayMusic()
                startActivity(ScanActivity::class.java)
            }
            binding.mainBottomBar.ivScan.onClick {
                pausePlayMusic()
                startActivity(ScanActivity::class.java)
            }
            binding.mainBottomBar.ivSetting.onClick {
                pausePlayMusic()
                startParentActivity(SettingFragment::class.java)
            }
            binding.mainBottomBar.btnSetting.onClick {
                pausePlayMusic()
                startParentActivity(SettingFragment::class.java)
            }
            binding.mainBottomBar.btnAi.onClick {
                if (binding.mainBottomBar.motionLayout.currentState == R.id.expand) {
                    showProgress()
                    viewModel.getChatTokenConfig()
                } else {
                    binding.mainBottomBar.motionLayout.transitionToState(R.id.expand)
                }
            }
            binding.mainBottomBar.ivLhh.onClick {
                if (binding.mainBottomBar.motionLayout.currentState == R.id.expand) {
                    showProgress()
                    viewModel.getChatTokenConfig()
                } else {
                    binding.mainBottomBar.motionLayout.transitionToState(R.id.expand)
                }
            }
            playBinding = ViewAudioPalyerBinding.inflate(LayoutInflater.from(this@MainActivity))
            binding.musicPlayer?.let { player ->
                playBinding?.apply {
                    player.addView(this.root)
                    seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
                        override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {

                        }

                        override fun onStartTrackingTouch(p0: SeekBar?) {

                        }

                        override fun onStopTrackingTouch(seekBar: SeekBar) {
                            player.seekToMusic((seekBar.progress * totalDuration / 100.0).toInt())
                        }
                    })
                    ivPlayback15s?.onClick {
                        player.seekToMusic(currentDuration - 15_000)
                    }
                    ivPalyForward15s?.onClick {
                        player.seekToMusic(currentDuration + 15_000)
                    }
                    ivBack.onClick {
                        if (currentPosition > 0) {
                            playByPosition(--currentPosition)

                        }
                    }
                    ivNext.onClick {
                        if (currentPosition < mTourGuideCommentaryList.size - 1) {
                            playByPosition(++currentPosition)
                        }
                    }
                    ivSpeedPlay.onClick {
                        speed = updateSpeed()
                        ivSpeedPlay.setImageResource(getPalySpeedImage(speed))
                        binding?.musicPlayer?.setPlaySpeed(speed)
                    }
                }
                player.setIconDrawable(ContextCompat.getDrawable(this@MainActivity, R.mipmap.ic_logo))
                player.setOnMusicStateListener(object : MusicPlayerView.OnMusicStateListener {
                    override fun onPrepared(duration: Int) {
                    }

                    override fun onError(what: Int, extra: Int) {
                    }

                    override fun onInfo(what: Int, extra: Int) {
                    }

                    override fun onMusicPlayComplete() {
                        //播放完成
                        playBinding?.ivPlayOrPause?.setImageResource(R.drawable.vector_pause)
                        if (hasNext()) {
                            playByPosition(++currentPosition)
                        } else {
                            mPodcastDetailBinding?.audioInclude?.ivPlayOrPause?.setImageResource(R.drawable.vector_play)
                            playBinding?.ivPlayOrPause?.setImageResource(R.drawable.vector_play)
                            isPlay = false
                        }
                    }

                    override fun onProgressUpdate(duration: Int, currentPos: Int) {
                        if (isSeekBarChanging.not()) {
                            playBinding?.seekBar?.progress = 100 * currentPos / duration
                            mPodcastDetailBinding?.audioInclude?.seekBar?.progress = 100 * currentPos / duration
                        }
                        currentDuration = currentPos
                        totalDuration = duration
                        playBinding?.apply {
                            tvCurrentTime.text = getGapTime(currentPos.toLong())
                            tvTotalTime.text = getGapTime(totalDuration.toLong())
                            ivPlayOrPause.setImageResource(R.drawable.vector_pause)
                        }
                        mPodcastDetailBinding?.audioInclude?.apply {
                            tvCurrentTime.text = getGapTime(currentPos.toLong())
                            tvTotalTime.text = getGapTime(totalDuration.toLong())
                            ivPlayOrPause.setImageResource(R.drawable.vector_pause)
                        }
                        val lectureContentList = mTourGuideCommentaryList.getOrNull(currentPosition)?.getLectureContentList()
                        lectureContentList?.filter { it.time.getFloat() * 1000 < currentDuration }?.lastIndex?.let {
                            if (currentSelectTextPosition != it) {
                                currentSelectTextPosition = it
                                mDetailAdapter?.notifyDataSetChanged()
                                mPodcastDetailBinding?.recyclerView?.scrollToPositionWithOffset(currentSelectTextPosition)
                            }
                        }
                    }

                    override fun onSeekComplete() {
                    }

                    override fun onHeadsetPullOut() {
                    }
                })
                playBinding?.ivPlayOrPause?.onClick {
                    if (isPlay) {
                        isPlay = false
                        player.pausePlayMusic()
                        playBinding!!.ivPlayOrPause.setImageResource(R.drawable.vector_play)
                    } else {
                        isPlay = true
                        player.resumePlayMusic()
                        playBinding!!.ivPlayOrPause.setImageResource(R.drawable.vector_pause)
                    }
                }
            }
            binding.recyclerView.let {
                it.addHorizontalDividerItemDecoration(10.dp(), android.R.color.transparent, true)
                it.layoutManager = LinearLayoutManager(this@MainActivity)
                mAdapter = KotlinAdapter.Builder<TourGuideCommentaryEntity, ItemPodcastBinding>(ItemPodcastBinding::class.java)
                    .addBindView { holder, item ->
                        run {
                            holder.binding?.apply {
                                tvDetail.visibility(currentPosition == holder.layoutPosition)
                                tvDetail.text = Strings.详情.toLanguage()
                                tvDetail.onClick {
                                    if (currentPosition == holder.layoutPosition) {
                                        showDetailDialog()
                                    } else {
                                        playByPosition(holder.layoutPosition)
                                    }
                                }
                                ivIcon.loadUrl(item?.exampleImage)
                                // 将自定义的 ShapeAppearanceModel 应用到 ShapeableImageView 上
                                tvTitle.text = item?.pointName.orEmpty()
                                if (currentPosition == holder.layoutPosition) {
                                    cardView.setCardBackgroundColor(ContextCompat.getColor(this@MainActivity, R.color.color_293078))
                                    tvTitle.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.white))
                                    tvDetail.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.white))
                                    ivMore.setImageResource(R.drawable.vector_more_white)
                                } else {
                                    cardView.setCardBackgroundColor(ContextCompat.getColor(this@MainActivity, R.color.white))
                                    tvTitle.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.color_333333))
                                    tvDetail.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.color_333333))
                                    ivMore.setImageResource(R.drawable.vector_more)
                                }
                            }
                        }
                    }
                    .onItemClick { holder, item ->
                        item?.run {
                            if (currentPosition == holder.layoutPosition) {
                                showDetailDialog()
                            } else {
                                playByPosition(holder.layoutPosition)
                            }
                        }
                    }
                    .setNewData(mTourGuideCommentaryList)
                    .create().also { adapter -> }
                val helper = QuickAdapterHelper.Builder(mAdapter!!).build().addAfterAdapter(PlaceHolderAdapter())
                it.adapter = helper.adapter
                playByPosition(currentPosition)
            }
        }
    }

    private fun pausePlayMusic() {
        isPlay = false
        binding?.musicPlayer?.pausePlayMusic()
        playBinding?.ivPlayOrPause?.setImageResource(R.drawable.vector_play)
    }


    private fun updateSpeed(): Float {
        return if (speed == 1f) {
            1.25f
        } else if (speed == 1.25f) {
            1.5f
        } else if (speed == 1.5f) {
            0.5f
        } else if (speed == 0.5f) {
            0.75f
        } else {
            1f
        }
    }

    private fun getPalySpeedImage(speed: Float): Int {
        return when (speed) {
            1.5f -> R.drawable.vector_paly_speed_1_5
            1.25f -> R.drawable.vector_paly_speed_1_25
            0.75f -> R.drawable.vector_paly_speed_0_75
            0.5f -> R.drawable.vector_paly_speed_0_5
            else -> R.drawable.vector_paly_speed_1
        }
    }

    private fun playByPosition(position: Int) {
        val mTourGuideCommentaryList: List<TourGuideCommentaryEntity> = GlobalCache.getTourGuideCommentary()
        val item = mTourGuideCommentaryList.getOrNull(position)
        if (item != null) {
            currentPosition = position
            isPlay = true
            binding?.apply {
                musicPlayer.startPlayMusic(LocalUrlUtils.getLocalUrl(item?.lectureAudio.orEmpty()))
                musicPlayer.setPlaySpeed(speed)
                //修改播放器按钮
                tvTitle.text = item?.pointName.orEmpty()
                imageView.loadUrl(item?.exampleImage.orEmpty(), isForceOriginalSize = true)
            }
            playBinding?.apply {
                ivPlayOrPause.setImageResource(R.drawable.vector_pause)
                ivBack.setImageResource(if (currentPosition == 0) R.drawable.vector_previous_gray else R.drawable.vector_previous)
                ivNext.setImageResource(if (hasNext().not()) R.drawable.vector_next_gray else R.drawable.vector_next)
            }
            mAdapter?.notifyDataSetChanged()
            binding?.recyclerView?.scrollToPositionWithOffset(currentPosition)
            mPodcastDetailBinding?.tvTitle?.setText(mTourGuideCommentaryList.getOrNull(currentPosition)?.pointName.orEmpty())
            mDetailAdapter?.setNewData(mTourGuideCommentaryList.getOrNull(currentPosition)?.lectureContentJson?.fromJson<List<LectureContentEntity>>())
        } else {
            //完成播放
            playBinding?.ivPlayOrPause?.setImageResource(R.drawable.vector_pause)
        }
    }

    private fun hasNext(): Boolean = currentPosition < mTourGuideCommentaryList.size - 1

    fun getGapTime(time: Long): String {
        val minutes = time / (1000 * 60)
        val second = (time - minutes * (1000 * 60)) / 1000
        var diffTime = "00:00:00"
        diffTime = if (minutes < 10) {
            "0$minutes"
        } else {
            "$minutes"
        }
        diffTime = if (second < 10) {
            "$diffTime:0$second"
        } else {
            "$diffTime:$second"
        }
        return diffTime
    }


    fun showDetailDialog() {
        XDialog.Builder(supportFragmentManager)
            .setViewBinding(FragmentPodcastDetailBinding::class.java) //设置弹窗展示的xml布局
            .setScreenWidthAspect(this, 1f)
            .setScreenHeightAspect(this, 1f)
            .setGravity(Gravity.BOTTOM) //设置弹窗展示位置
            .setTag("DetailDialog")
            .setDimAmount(0.8f) //设置弹窗背景透明度(0-1f)
            .setCancelableOutside(false) //弹窗在界面外是否可以点击取消
            .setDialogAnimationRes(R.style.animate_dialog) //设置弹窗动画
            .setOnDismissListener {
                mPodcastDetailBinding = null
                mDetailAdapter = null
            }
            .setOnBindViewListener(object : OnBindViewListener<FragmentPodcastDetailBinding> {
                override fun onBind(itemBinding: FragmentPodcastDetailBinding, xDialog: XDialog) {
                    mPodcastDetailBinding = itemBinding
                    val mSpotInfo: SpotInfoEntity? = GlobalCache.getSpotInfo()
                    mSpotInfo?.welcomeData?.firstOrNull()?.let {
                        itemBinding.ivBackground.loadUrl(it.url.orEmpty())
                    }
//                    val includedBinding: ViewAudioPalyerBinding = ViewAudioPalyerBinding.bind(binding.audioInclude)
                    itemBinding.ivDismissDialog.onClick {
                        xDialog.dismiss()
                    }
                    itemBinding.tvTitle.text = mTourGuideCommentaryList.getOrNull(currentPosition)?.pointName.orEmpty()
                    itemBinding.audioInclude.let {
                        if (totalDuration > 0) {
                            it.seekBar.progress = 100 * currentDuration / totalDuration
                        }
                        it.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
                            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                            }

                            override fun onStartTrackingTouch(p0: SeekBar?) {
                            }

                            override fun onStopTrackingTouch(seekBar: SeekBar) {
                                binding?.musicPlayer?.seekToMusic((seekBar.progress * totalDuration / 100.0).toInt())
                            }
                        })
                        it.ivBack.setImageResource(if (currentPosition == 0) R.drawable.vector_previous_gray else R.drawable.vector_previous)
                        it.ivNext.setImageResource(if (hasNext().not()) R.drawable.vector_next_gray else R.drawable.vector_next)
                        it.ivPlayOrPause.setImageResource(R.drawable.vector_pause)
                        it.ivSpeedPlay.setImageResource(getPalySpeedImage(speed))
                        playBinding?.ivSpeedPlay?.setImageResource(getPalySpeedImage(speed))
                        it.tvCurrentTime.text = getGapTime(currentDuration.toLong())
                        it.tvTotalTime.text = getGapTime(totalDuration.toLong())
                        it.ivPalyForward15s.onClick {
                            binding?.musicPlayer?.seekToMusic(currentDuration + 15_000)
                        }
                        it.ivPlayback15s.onClick {
                            binding?.musicPlayer?.seekToMusic(currentDuration - 15_000)
                        }
                        it.ivSpeedPlay.onClick { _ ->
                            speed = updateSpeed()
                            it.ivSpeedPlay.setImageResource(getPalySpeedImage(speed))
                            binding?.musicPlayer?.setPlaySpeed(speed)
                        }
                        it.ivPlayOrPause?.onClick { _ ->
                            if (isPlay) {
                                pausePlayMusic()
                                it.ivPlayOrPause.setImageResource(R.drawable.vector_play)
                            } else {
                                isPlay = true
                                binding?.musicPlayer?.resumePlayMusic()
                                it.ivPlayOrPause.setImageResource(R.drawable.vector_pause)
                            }
                        }
                        it.ivPlayOrPause.setImageResource(if (isPlay) R.drawable.vector_pause else R.drawable.vector_play)
                        it.ivSpeedPlay.setImageResource(getPalySpeedImage(speed))
                        it.ivNext.onClick { _ ->
                            if (hasNext()) {
                                playByPosition(++currentPosition)
                                it.ivBack.setImageResource(if (currentPosition == 0) R.drawable.vector_previous_gray else R.drawable.vector_previous)
                                it.ivNext.setImageResource(if (hasNext().not()) R.drawable.vector_next_gray else R.drawable.vector_next)
                            }
                        }
                        it.ivBack.onClick { _ ->
                            if (currentPosition > 0) {
                                playByPosition(--currentPosition)
                                it.ivBack.setImageResource(if (currentPosition == 0) R.drawable.vector_previous_gray else R.drawable.vector_previous)
                                it.ivNext.setImageResource(if (hasNext().not()) R.drawable.vector_next_gray else R.drawable.vector_next)
                            }
                        }
                    }
                    itemBinding.recyclerView.adapter = KotlinAdapter.Builder<LectureContentEntity, ItemPodcastTextDescriptionBinding>(ItemPodcastTextDescriptionBinding::class.java)
                        .addBindView { holder, item ->
                            run {
                                holder.binding?.apply {
                                    this.tvDescription.text = item?.text.orEmpty()
                                    this.tvDescription.setTextColor(
                                        ContextCompat.getColor(
                                            this@MainActivity,
                                            if (currentSelectTextPosition == holder.layoutPosition) R.color.color_293078 else R.color.color_333333
                                        )
                                    )
                                }
                            }
                        }
                        .setNewData(mTourGuideCommentaryList.getOrNull(currentPosition)?.lectureContentJson?.fromJson<List<LectureContentEntity>>())
                        .create()
                        .also {
                            mDetailAdapter = it
                        }
                }
            })
            .setOnKeyListener { dialog, keyCode, event ->
                false
            }
            .create() //创建TDialog
            .show() //展示
    }


    @Subscribe
    fun onMessage(e: SearchResultEvent) {
        currentPosition = mTourGuideCommentaryList.indexOfFirst { TextUtils.equals("${it.orderBy}", e.content) }
        playByPosition(currentPosition)
    }

    @Subscribe
    fun onMessage(e: ScanResultEvent) {
        currentPosition = mTourGuideCommentaryList.indexOfFirst { TextUtils.equals("${it.orderBy}", e.content) }
        playByPosition(currentPosition)
    }

    @Subscribe
    fun onMessage(e: OnLanguageSwitchEvent) {
        currentPosition = 0
        mTourGuideCommentaryList = GlobalCache.getTourGuideCommentary()
        mAdapter?.setNewData(mTourGuideCommentaryList)
        playBinding?.ivSpeedPlay?.setImageResource(getPalySpeedImage(speed))
        playByPosition(currentPosition)
        binding?.root?.postDelayed({
            pausePlayMusic()
        }, 200)
        binding.apply {
            tvTitle.setText(mTourGuideCommentaryList.getOrNull(currentPosition)?.pointName.orEmpty())
            mainBottomBar.btnScan.setText(Strings.景点扫码.toLanguage())
            mainBottomBar.btnSetting.setText(Strings.更多.toLanguage())
            mainBottomBar.btnAi.setText(if (LanguageManager.currentLangCode == "en") Strings.AI翻译.toLanguage() else Strings.AI对话.toLanguage())
            mainBottomBar.ivLhh.setImageResource(if (LanguageManager.currentLangCode == "en") R.drawable.vector_main_translate else R.mipmap.lhh)
        }
        val mSpotInfo: SpotInfoEntity? = GlobalCache.getSpotInfo()
        mSpotInfo?.welcomeData?.firstOrNull()?.let {
            binding.ivBackground.loadUrl(it.url.orEmpty())
        }
    }
    //提醒过的
    var remindedLocationPositions: MutableMap<Int,Long> = mutableMapOf()
    var locationPosition: Int = -1
    override fun onStart() {
        super.onStart()
        lifecycleScope.launch {
            locationViewModel.locationState.collect { location ->
                location?.let {
                    mTourGuideCommentaryList.map { entity ->
                        entity.distance = AMapUtils.calculateLineDistance(LatLng(location.latitude, location.longitude), LatLng(entity.latitude, entity.longitude))
                        entity
                    }
                        .filter { it.distance <= 15 && it.isTriggered == 1 }
                        .sortedBy { it.distance }
                        .firstOrNull()?.let { entity ->
                            if (remindedLocationPositions.contains(entity.orderBy).not()  && currentPosition != mTourGuideCommentaryList.indexOf(entity)) {
                                //播放提示音
                                MediaPlayerUtils.getInstance().playAudioByAssets("location_tip.wav")
                                locationPosition = mTourGuideCommentaryList.indexOf(entity)
                                binding.cvLocation.visible()
                                binding.cvLocation.postDelayed({
                                     binding.cvLocation.gone()
                                },30*1000)//30秒后自动隐藏
                                binding.cvLocation.onClick {
                                    currentPosition = locationPosition
                                    playByPosition(currentPosition)
                                    binding.cvLocation.gone()
                                }
                                binding.sivIcon.loadUrl(entity.exampleImage)
                                binding.tvNearby.text = Strings.附近.toLanguage()
                            }
                            //加入记录，避免重复提醒
                            if (remindedLocationPositions.contains(entity.orderBy).not()){
                                remindedLocationPositions.put(entity.orderBy,System.currentTimeMillis())
                            }
                            //大于5分钟就清除
                            remindedLocationPositions.entries.removeIf { System.currentTimeMillis() - it.value > 5*60*1000 }
                        }
                }

            }
        }
    }

    override fun onResume() {
        super.onResume()
        requestLocation()
    }

    fun requestLocation() {
        locationViewModel.startLocation(locationOption = AMapLocationClientOption().apply {
            locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
            isOnceLocation = false
            interval = 6000L //6s一次
        })
    }

    override fun onPause() {
        super.onPause()
        locationViewModel.stopLocation()
    }

    override fun onStop() {
        super.onStop()
    }



    @Subscribe
    fun onMessageEvent(e: PausePodcastEvent) {
        pausePlayMusic()
    }
}